package com.redfox.newapp.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.redfox.newapp.R;
import com.redfox.newapp.adapter.PhotoAdapter;
import com.redfox.newapp.utils.HttpRequest;

import org.json.JSONArray;
import org.json.JSONObject;
import com.jcodecraeer.xrecyclerview.XRecyclerView;


import java.util.ArrayList;
import java.net.URLEncoder;

/**
 * Created by redfox on 2017/3/15.
 */

public class PhotoFragment extends Fragment implements Runnable, Handler.Callback {

    private final String TAG = "PhotoFragment";
    private final int WM_PHOTO_COMPLETE = 0x1001;

    private XRecyclerView mRecyclerView;
    private PhotoAdapter mAdatper;
    private Handler mHandler;
    private int mPage = 1;




    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.photo_frag_layout, container, false);

        mRecyclerView = (XRecyclerView) v.findViewById(R.id.photo_view);
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        //mRecyclerView.setAnimation();
        //mRecyclerView.addItemDecoration(new DividerGridItemDecoration(this));
        mRecyclerView.setLoadingMoreEnabled(true);
        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mRecyclerView.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                mRecyclerView.setLoadingMoreEnabled(false);
                loadNextPage();
            }
        });


        mAdatper = new PhotoAdapter(container.getContext());
        mRecyclerView.setAdapter(mAdatper);


        mHandler = new Handler(this);
        Thread thread = new Thread(this);
        thread.start();


        return v;
    }

    public static PhotoFragment newInstance(String param) {
        PhotoFragment fragment = new PhotoFragment();
        Bundle bundle = new Bundle();
        bundle.putString("param", param);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void run() {
        ArrayList<PhotoAdapter.PhotoItem> photos  = new ArrayList<>();
        try {
            HttpRequest request = HttpRequest.get("http://gank.io/api/data/" + URLEncoder.encode("福利", "utf-8") + "/30/" + mPage);
            if (request.ok()) {
                JSONObject json = new JSONObject(request.body());
                if (json.getBoolean("error") == false) {
                    JSONArray array = json.getJSONArray("results");
                    for (int i = 0; i < array.length(); ++i) {
                        PhotoAdapter.PhotoItem item = new PhotoAdapter.PhotoItem();
                        item.url = array.getJSONObject(i).getString("url");
                        photos.add(item);
                    }
                }

            }
        }
        catch (Exception e) {
            Log.d(TAG, "run: " + e.getMessage());
        }

        Message msg = mHandler.obtainMessage(WM_PHOTO_COMPLETE, photos);
        mHandler.sendMessage(msg);

    }

    @Override
    public boolean handleMessage(Message msg) {
        if ((msg.what == WM_PHOTO_COMPLETE)) {
            ArrayList<PhotoAdapter.PhotoItem> array = (ArrayList<PhotoAdapter.PhotoItem>) msg.obj;
            for (PhotoAdapter.PhotoItem item : array)
                mAdatper.addItem(item);

            mAdatper.notifyDataSetChanged();
            mRecyclerView.loadMoreComplete();
            mRecyclerView.setLoadingMoreEnabled(true);
        }
        return false;
    }


    public void loadNextPage() {
        mPage++;
        Thread thread = new Thread(this);
        thread.start();
    }
}
